package com.springboot.demo.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.springboot.demo.constant.CommonConstant;

/**
 * socketServer
 *
 * @author supu
 * @since 2020-11-24 17:40
 **/
public class SocketServer {
    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(8, 8, 60, TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(20), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(CommonConstant.LOCAL_PORT));

            while (true){
                Socket client = serverSocket.accept();
                if(client != null){
                    EXECUTOR.execute(() -> {
                        try {
                            // 读取数据
                            InputStream inputStream = client.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                            String content = null;
                            while ((content = reader.readLine()) != null && !"".equals(content)){
                                System.out.println(content);
                            }

                            // 写回内容给客户端
                            BufferedWriter bufferedWriter =
                                    new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                            bufferedWriter.write(CommonConstant.getResponseContent());
                            bufferedWriter.flush();
                            client.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
